from src.models.database import db
from datetime import datetime
import json

class MetasoQueryData(db.Model):
    """Metaso查询数据表"""
    __tablename__ = 'metaso_query_data'
    
    id = db.Column(db.Integer, primary_key=True)
    query_id = db.Column(db.String(50), unique=True, nullable=False, index=True)  # 查询唯一ID
    query_text = db.Column(db.Text, nullable=False)  # 查询问题
    query_time = db.Column(db.DateTime, default=datetime.utcnow)  # 查询时间
    
    # Metaso API返回的原始数据
    total_results = db.Column(db.Integer)  # 总结果数
    credits_used = db.Column(db.Integer)   # 使用的积分
    
    # GLM4.5分析结果
    analysis_result = db.Column(db.Text)   # GLM4.5分析后的准确结果
    analysis_time = db.Column(db.DateTime) # 分析完成时间
    confidence_score = db.Column(db.Float) # 置信度分数
    
    # 状态信息
    status = db.Column(db.String(20), default='pending')  # pending, running, completed, failed
    error_message = db.Column(db.Text)  # 错误信息
    
    # 板块信息
    sector_id = db.Column(db.String(50))  # 板块ID (pharma_formulations, pharma_apis, plant_protection, animal_health)
    sector_name = db.Column(db.String(100))  # 板块名称
    
    # AI分析结果字段
    industry_cagr = db.Column(db.Float)  # 行业复合年增长率
    market_stage_cagr = db.Column(db.Float)  # 市场所处阶段及未来影响业绩的预期评估复合年增长率
    ai_analysis_result = db.Column(db.Text)  # AI分析的完整结果
    
    # 元数据
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self, include_sources=False):
        result = {
            'id': self.id,
            'query_id': self.query_id,
            'query_text': self.query_text,
            'query_time': self.query_time.isoformat() if self.query_time else None,
            'total_results': self.total_results,
            'credits_used': self.credits_used,
            'analysis_result': self.analysis_result,
            'analysis_time': self.analysis_time.isoformat() if self.analysis_time else None,
            'confidence_score': self.confidence_score,
            'status': self.status,
            'error_message': self.error_message,
            'sector_id': self.sector_id,
            'sector_name': self.sector_name,
            'industry_cagr': self.industry_cagr,
            'market_stage_cagr': self.market_stage_cagr,
            'ai_analysis_result': self.ai_analysis_result,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'sources_count': self.total_results  # 添加前端期望的字段
        }
        
        if include_sources:
            # 获取关联的sources数据
            sources = MetasoWebpageData.query.filter_by(query_data_id=self.id).order_by(MetasoWebpageData.position).all()
            result['sources'] = [source.to_dict() for source in sources]
        
        return result


class MetasoWebpageData(db.Model):
    """Metaso返回的网页数据表"""
    __tablename__ = 'metaso_webpage_data'
    
    id = db.Column(db.Integer, primary_key=True)
    query_data_id = db.Column(db.Integer, db.ForeignKey('metaso_query_data.id'), nullable=False)  # 关联查询数据
    position = db.Column(db.Integer)  # 在结果中的位置
    
    # 网页基本信息
    title = db.Column(db.String(500))  # 标题
    link = db.Column(db.String(1000))  # 链接
    snippet = db.Column(db.Text)       # 摘要内容
    score = db.Column(db.String(20))   # 相关性评分
    date = db.Column(db.String(100))   # 日期信息
    
    # 元数据
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': self.id,
            'query_data_id': self.query_data_id,
            'position': self.position,
            'title': self.title,
            'link': self.link,
            'snippet': self.snippet,
            'score': self.score,
            'date': self.date,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
